//
//  UserAccountViewModel.swift
//  新浪微博
//
//  Created by 赵春浩 on 15/12/15.
//  Copyright © 2015年 DreamFlyingCow. All rights reserved.
//

import UIKit
import AFNetworking

// 封装网络请求和业务逻辑
class UserAccountViewModel: NSObject {
// 定义用户模型对象的属性
    var userAccount: UserAccount?
    
    override init() {
        // 对象的构造分两步
        // 先构造本身 在构造父类
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    // 计算型属性  用户是否登录
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }
    // 用户头像的 url
    var headURL: NSURL? {
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    
    // 用户名
    var userName: String? {
        
        
        return userAccount?.name
    }
    
    // 用户的 token
    var token: String? {
        return userAccount?.access_token
    }
    
    // MARK: 加载用户 token(请求标识)
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 参数是要封装成字典的
        let parameters = ["client_id" : client_id, "client_secret" : client_secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        let AFN = AFHTTPSessionManager()
        // 添加反序列化的文件类型
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: { (p) -> Void in
            print(p)
            
            }, success: { (_, result) -> Void in
            print(result)
            if let dict = result as? [String : AnyObject] {
                // 字典转模型
                let userAccount = UserAccount(dict: dict)
                self.loadUserInfo(userAccount, finished:finished)
            }
            
            
            }) { (_, error) -> Void in
                print(error)
                finished(isSuccess: false)
        }
    }
    
    // MARK: 获取用户的信息
    private func loadUserInfo(account: UserAccount, finished: (isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        if let token = account.access_token, userId = account.uid {
            let parameters = ["access_token" : token, "uid" : userId]
            let AFN = AFHTTPSessionManager()
            AFN.GET(urlString, parameters: parameters, progress: { (_) -> Void in
                
                }, success: { (_, result) -> Void in
                    if let dict = result {
                        let avatar_large = dict["avatar_large"] as! String
                        let name = dict["name"] as! String
                        // 给 account 对象的属性赋值
                        account.name = name
                        account.avatar_large = avatar_large
                        
                        // 获取用户信息的完整自定义对象
                        // 存储自定义对象
                        account.saveAccount()
                        // 执行成功之后的回调
                        finished(isSuccess: true)
                    }
                }, failure: { (_, error) -> Void in
                    print(error)
                    finished(isSuccess: false)
            })
        }
        
    }
    
}
